package com.qhyiyun.baseweb.aspect;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qhyiyun.baseweb.util.CustomResponse;
import com.qhyiyun.baseweb.util.Sm4Util;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class ResponseEncryptAspect {
    @Value("${sm4.key}")
    private String sm4Key;

    Logger logger=LoggerFactory.getLogger(ResponseEncryptAspect.class);
    @AfterReturning(pointcut = "execution(* com.qhyiyun.baseweb.controller..*(..))", returning = "result")
    public Object encryptResponse(Object result) {
        try {
            if (result instanceof CustomResponse) {
                CustomResponse<Object> response = (CustomResponse<Object>) result;
                String jsonString = new ObjectMapper().writeValueAsString(response.getData());
                String encryptedData = Sm4Util.encrypt(jsonString, null,null,null);
                response.setData(encryptedData); // 需要强制转换到Object
                System.out.println("Encrypted response: " + response);
                return response;
            }
            return result;
        } catch (Exception e) {
            throw new RuntimeException("Failed to encrypt response", e);
        }
    }
}

